package no.uib.hplims.views.peptides;

import java.util.ArrayList;
import java.util.List;

import no.uib.hplims.models.peptideinformation.PeptideInformation;

import org.vaadin.appfoundation.persistence.data.AbstractPojo;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;

public abstract class AbstractInformationView<T extends AbstractPojo> extends
		VerticalLayout implements Button.ClickListener {

	private static final long serialVersionUID = 2688816212273998980L;
	
	protected PeptideInformation peptideInformation;
	protected Class<T> clazz;

	protected Table itemTable;
	protected BeanItemContainer<T> itemContainer;

	protected Button newButton;
	protected Button editButton;
	protected boolean editMode = false;
	
	protected DefaultFieldFactory itemTableFieldFactory;

	protected final ArrayList<Object> visibleColumnIds = new ArrayList<Object>();
	protected final ArrayList<String> visibleColumnLabels = new ArrayList<String>();

	public AbstractInformationView(Class<T> theClass, PeptideInformation pi) {
		this.clazz = theClass;
		this.peptideInformation = pi;
	}

	protected void init(List<T> items) {
		this.setMargin(true, true, false, true);
		this.setSpacing(true);

		// Add toolbar
		addComponent(getToolbar());

		// Add table with information
		addComponent(setupWithData(items));
		addListeners();
	}

	private Table setupWithData(List<T> items) {
		if (itemContainer == null) {
			itemContainer = new BeanItemContainer<T>(clazz);
		}

		itemContainer.addAll(items);

		itemTable = new Table();
		itemTable.setSizeFull();
		itemTable.setStyleName(Runo.TABLE_SMALL);
		itemTable.setContainerDataSource(itemContainer);
		itemTable.setImmediate(true);
		// Display 6 storage at the time in the table
		itemTable.setPageLength(6);

		return itemTable;
	}

	private Component getToolbar() {
		HorizontalLayout toolbar = new HorizontalLayout();

		newButton = new Button("New");
		newButton.setImmediate(true);
		toolbar.addComponent(newButton);
		
		editButton = new Button("Edit");
		editButton.setImmediate(true);
		toolbar.addComponent(editButton);

		return toolbar;
	}

	protected abstract void addVisibleColumns();
	
	protected void addListeners() {
		newButton.addListener(this);
		editButton.addListener(this);
	}
	
	protected abstract DefaultFieldFactory getFieldFactory();

}
